import Icon from '@/components/Icon';
import NavBar from '@/components/NavBar';
import { useAppSelector } from '@/store';
import {
  clearHistoriesAction,
  clearSuggestAction,
  getSuggestAction,
  saveHistoryAction,
} from '@/store/action/search';
import { removeLocalHistories, setLocalHistories } from '@/utils/storage';
import { Toast } from 'antd-mobile';
import DOMPurify from 'dompurify';
import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useHistory } from 'react-router-dom';

// import classnames from 'classnames';
import styles from './index.module.scss';
// React解析标签,在标签里面打html
// // 文字高亮，正则文字高亮
// 大小写不能改，（）代表分组，$1占位符
// 空字符不能发送请求
// 渲染历史，限制历史记录数量不超过10条
const hightLight = (keyword: string, item: string) => {
  // const reg = new RegExp(`(${keyword})`, 'gi'); //第一个参数是匹配什么字段，第二个是什么匹配模式，全局与不在意大小

  // return item.replace(reg, `<span onclick="alert(123)" >$1</span>`);
  const reg = new RegExp(`(${keyword})`, 'gi');
  return item.replace(reg, `<span>$1</span>`);
};
export default function Search() {
  const [keyword, setKeyword] = useState('');
  const dispatch = useDispatch();
  const { suggestion, histories } = useAppSelector((state) => state.search);
  const history = useHistory();
  // 防抖
  let timeIdRef = useRef(-1);
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    // 记得加window,Ref取值要current
    setKeyword(e.target.value);
    window.clearTimeout(timeIdRef.current);
    if (!e.target.value.trim()) return;

    timeIdRef.current = window.setTimeout(() => {
      dispatch(getSuggestAction(e.target.value));
    }, 500);
  };
  // 先输入再删除,还是有搜索历史,侦听器
  useEffect(() => {
    if (!keyword.trim()) {
      dispatch(clearSuggestAction());
    }
  }, [keyword, dispatch]);

  // 清除定时器
  useEffect(() => {
    window.clearTimeout(timeIdRef.current);
    // 卸载组件得时候清空一下
    dispatch(clearSuggestAction());
  }, [dispatch]);
  //清空历史
  const ClearSearchFn = () => {
    setKeyword('');
    dispatch(clearSuggestAction());
  };
  const searchFn = () => {
    // 判空
    if (!keyword.trim()) return Toast.show({ content: '不能为空' });

    dispatch(saveHistoryAction(keyword));
    handleGotoResult(keyword);
  };
  // 保存到本地
  useEffect(() => {
    setLocalHistories(histories);
  }, [histories]);
  const handleClearHistores = () => {
    // 2. 清除redux
    dispatch(clearHistoriesAction());
    // 3. 清除缓存
    removeLocalHistories();
  };
  // 点击记录跳转
  const handleGotoResult = (key: string) => {
    history.push('/search/result?q=' + key);
    // history.push('/search/result', { keyword: key });
  };
  // 限制10条
  const tenHistroies = histories.slice(0, 10);
  // console.log(tenHistroies);

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar
        right={
          <span className="search-text" onClick={searchFn}>
            搜索
          </span>
        }
      >
        <div className="navbar-search">
          <Icon type="iconbtn_search" className="icon-search" />

          <div className="input-wrapper">
            {/* 输入框 */}
            <input
              type="text"
              placeholder="请输入关键字搜索"
              value={keyword}
              onChange={(e) => handleChange(e)}
              onKeyDown={(e) => e.key === 'Enter' && searchFn()}
            />

            {/* 清空输入框按钮 */}
            {keyword.trim() && (
              <Icon
                type="iconbtn_tag_close"
                className="icon-close"
                onClick={ClearSearchFn}
              />
            )}
          </div>
        </div>
      </NavBar>

      {/* 搜索历史 */}
      {/* 互s用逻辑与加强制类型装换 */}
      {!keyword && (
        <div className="history" style={{ display: 'block' }}>
          <div className="history-header">
            <span>搜索历史</span>
            <span onClick={handleClearHistores}>
              <Icon type="iconbtn_del" />
              清除全部
            </span>
          </div>
          {/* 历史记录 */}

          <div className="history-list">
            {tenHistroies.map((item, index) => {
              return (
                <span
                  className="history-item"
                  key={index}
                  onClick={() => handleGotoResult(item)}
                >
                  {item}
                  <span className="divider"></span>
                </span>
              );
            })}
          </div>
        </div>
      )}
      {/* 搜素建议结果列表 */}
      <div className="search-result">
        {suggestion.map((item, index) => {
          return (
            // 点击搜索条目跳转传参
            <div
              className="result-item"
              key={index}
              onClick={() => handleGotoResult(item)}
            >
              <Icon className="icon-search" type="iconbtn_search" />
              {/* 两个———html ，不能与children一起写*/}
              <div
                className="result-value"
                dangerouslySetInnerHTML={{
                  __html: DOMPurify.sanitize(hightLight(keyword, item)),
                }}
              >
                {/* <span>{'高亮'}</span>
                {item} */}
                {/* {hightLight(keyword, item)} */}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
